import 'package:flutter/material.dart';
import 'package:flutter2/colors.dart';
import 'package:flutter2/utils/log.dart';
import 'package:flutter2/widget/title_bar.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebPage extends StatefulWidget {
  const WebPage({
    super.key,
    this.url,
    this.title,
  });

  final String? url;
  final String? title;

  @override
  State<WebPage> createState() => _WebPageState();
}

class _WebPageState extends State<WebPage> {
  late WebViewController _controller;

  @override
  void initState() {
    super.initState();
    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..enableZoom(false)
      ..canGoBack()
      ..setOverScrollMode(WebViewOverScrollMode.never)
      ..setHorizontalScrollBarEnabled(false)
      ..setNavigationDelegate(
        NavigationDelegate(
          onNavigationRequest: (request) {
            if (request.url.startsWith("http")) {
              LogUtils.log(request.url);
              return NavigationDecision.navigate;
            } else {
              LogUtils.log(request.url);
              launchUrl(Uri.parse(request.url));
              return NavigationDecision.prevent;
            }
          },
          onProgress: (progress) {
            value = progress / 100;
            setState(() {});
          },
        ),
      )
      ..loadRequest(Uri.parse(widget.url ?? ""));
  }

  double value = 0.0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: TitleBar.buildAppBar(title: widget.title),
      body: Column(
        children: [
          Offstage(
            offstage: value == 1,
            child: LinearProgressIndicator(
              backgroundColor: Colors.white,
              value: value,
              color: btnColor,
            ),
          ),
          Expanded(
            child: WebViewWidget(controller: _controller),
          ),
        ],
      ),
    );
  }
}
